package controllers

import (
	"gitee.com/igolang/imoney/internal/app/system/services"
	"gitee.com/igolang/imoney/internal/common/httpResp"
	"gitee.com/igolang/imoney/internal/models/dao"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

var Config = &config{}

type config struct{}

func (c *config) List(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.Config.List(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}

func (c *config) Detail(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	id := cast.ToInt64(ctx.Param("id"))
	if id == 0 {
		httpResp.ErrorResponse(httpResp.ErrCodeInvalidParams, r)
		return
	}

	row, err := dao.SysConfig.Where(dao.SysConfig.ConfigID.Eq(id)).Take()
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = row
}

func (c *config) Get(ctx *gin.Context) {
	key := ctx.Param("key")
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	r.Data = services.Config.Get(key)
}

func (c *config) Export(ctx *gin.Context) {
	r := httpResp.Response()
	b, err := services.Config.Export(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		httpResp.JSON(ctx, r)
		return
	}
	httpResp.Export(ctx, b, "xlsx")
}

func (c *config) Save(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Config.Save(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}

func (c *config) RefreshCache(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Config.RefreshCache(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}

func (c *config) Delete(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Config.Delete(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}
